<?php
namespace qiniu;

use qiniu\rs\PutPolicy;
use yii\base\InvalidConfigException;
use yii\bootstrap\Widget;
use yii\di\Instance;
use yii\helpers\Html;

class Form extends Widget
{
    const ACTION_URL = 'http://upload.qiniu.com';

    public $customFields = [];

    public $putPolicy = [];

    public $key;

    public $accept;

    /** @var Qiniu */
    protected $qiuniu;

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        parent::init();

        $this->qiuniu = Instance::ensure('qiniu', Qiniu::className());

        $putPolicy = new PutPolicy($this->putPolicy);

        if ((strpos($putPolicy->scope, ':') !== false) && !isset($this->key)) {
            throw new InvalidConfigException('key 必须指定');
        }

        $this->options['enctype'] = 'multipart/form-data';

        echo Html::beginForm(self::ACTION_URL, 'post', $this->options);

        foreach ($this->customFields as $name => $value) {
            echo Html::hiddenInput('x:'. $name, $value);
        }

        if (isset($this->accept)) {
            echo Html::hiddenInput('accept', $this->accept);
        }

        if (isset($this->key)) {
            echo Html::hiddenInput('key', $this->key);
        }

        echo Html::hiddenInput('token', $this->qiuniu->generateUploadToken($putPolicy));
    }

    public function run()
    {
        echo Html::endForm();
    }
}
